package com.ym521.imgcrop.crop;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.ym521.imgcrop.R;
import com.ym521.imgcrop.base.Constant;
import com.ym521.imgcrop.base.CropRequest;
import com.ym521.imgcrop.base.CropResultCode;
import com.ym521.imgcrop.widget.CircleCropView;
import com.ym521.imgcrop.widget.ImageTouchView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Ym
 * E-mail: 2435970206@qq.com
 * createTime:2023/12/29
 * explain: 圆形裁剪
 */
public class CircleCropActivity extends AppCompatActivity {
    private static final String TAG = "CircleCropActivity";
    private ImageTouchView itvImage;
    private CircleCropView ccpCrop;
    private ImageView ivPreView;
    private ImageView ivBreak;
    private TextView tvCrop, tvSave, tvReCrop;
    private Bitmap bitmapCrop = null;

    private Intent intent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.circlecrop_activity);
        intent = new Intent();
        initView();
        if (getIntent().getSerializableExtra(Constant.REQUEST_KEY) == null) {
            setResult(CropResultCode.FAIL.getCode(),intent);
            finish();
            return;
        }
        CropRequest request = null;
        try {
            request = (CropRequest) getIntent().getSerializableExtra(Constant.REQUEST_KEY);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        if (request == null) {
            setResult(CropResultCode.FAIL.getCode(),intent);
            finish();
            return;
        }
        if (request.getExtra() != null)
            intent.putExtra(Constant.REQUEST_EXTRA, request.getExtra());
        if (request.getDrawableRes() == 0 && request.getIamgePath() == null) {
            setResult(CropResultCode.FAIL.getCode(), intent);
            finish();
            return;
        }
        if (request.getWidthRatio() > 0)
            ccpCrop.setWidthRatio(request.getWidthRatio());
        if (request.getDrawableRes() != 0) {
            itvImage.setImageResource(request.getDrawableRes());
        }
        if (request.getIamgePath() != null) {
            itvImage.setImageFile(request.getIamgePath(), 1);
        }
        tvCrop.setOnClickListener(v -> {
            imageCrop();
        });
        tvReCrop.setOnClickListener(v -> {
            imageReCrop();
        });
        tvSave.setOnClickListener(v -> {
            if (bitmapCrop != null)
                saveCropImage(bitmapCrop);
        });

        ivBreak.setOnClickListener(v -> {
            setResult(CropResultCode.CANCEL.getCode(), intent);
            finish();
        });
    }

    @Override
    public void onBackPressed() {
        setResult(CropResultCode.CANCEL.getCode(), intent);
        finish();
    }

    private void initView() {
        itvImage = findViewById(R.id.itvImage);
        ccpCrop = findViewById(R.id.ccpCrop);
        ivPreView = findViewById(R.id.ivPreView);
        tvCrop = findViewById(R.id.tvCrop);
        tvSave = findViewById(R.id.tvSave);
        tvReCrop = findViewById(R.id.tvReCrop);
        ivBreak = findViewById(R.id.ivBreak);
    }

    private void imageCrop() {
        bitmapCrop = itvImage.getBitmap(ccpCrop);
        if (bitmapCrop != null) {
            ivPreView.setImageBitmap(bitmapCrop);
        }
        itvImage.setVisibility(View.GONE);
        ccpCrop.setVisibility(View.GONE);
        tvCrop.setVisibility(View.GONE);
        ivPreView.setVisibility(View.VISIBLE);
        tvSave.setVisibility(View.VISIBLE);
        tvReCrop.setVisibility(View.VISIBLE);
    }

    private void imageReCrop() {
        itvImage.setVisibility(View.VISIBLE);
        ccpCrop.setVisibility(View.VISIBLE);
        tvCrop.setVisibility(View.VISIBLE);
        ivPreView.setVisibility(View.GONE);
        tvSave.setVisibility(View.GONE);
        tvReCrop.setVisibility(View.GONE);
    }


    private void saveCropImage(Bitmap cropImage) {
        Thread saveThread = new Thread(() -> {
            String fileName = UUID.randomUUID().toString() + ".png";
            File cropImageFile = new File(getExternalCacheDir().getAbsolutePath() + Constant.CROP_SAVE, fileName);
            try {
                if (!cropImageFile.getParentFile().exists()) {
                    cropImageFile.getParentFile().mkdirs();
                }
                cropImageFile.createNewFile();
                FileOutputStream out = new FileOutputStream(cropImageFile);
                cropImage.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
                this.runOnUiThread(() -> {
                    intent.putExtra(Constant.CROP_PATH_KEY, cropImageFile.getAbsolutePath());
                    setResult(CropResultCode.SUCCESS.getCode(), intent);
                });
            } catch (IOException e) {
                Log.e(TAG, e.toString());
                this.runOnUiThread(() -> {
                    setResult(CropResultCode.FAIL.getCode(), intent);
                });
            }
            this.runOnUiThread(this::finish);
        });
        saveThread.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bitmapCrop = null;
    }

}
